package main

import (
	"fmt"
	"github.com/zinx/znet"
	"io"
	"net"
	"time"
)

/**
* 客户端
* @Author: WuZhiHang
* @Date: 2020/10/16 10:02 下午
 */

func main() {
	fmt.Println("client start")
	// 连接远程服务器，得到conn连接
	conn, err := net.Dial("tcp", "127.0.0.1:8999")
	if err != nil {
		fmt.Println("client start err:", err)
		return
	}
	// 连接调用Write
	for {
		// 发送封包的msg消息
		dp := znet.NewDataPack()
		binaryMsg, err := dp.Pack(znet.NewMsgPackage(0, []byte("zinx 0.5")))
		if err != nil {
			fmt.Println("pack err", err)
		}
		if _, err = conn.Write(binaryMsg); err != nil {
			fmt.Println("write err:", err)
			break
		}

		// 服务器回复message
		binaryHead := make([]byte, dp.GetHeadLen())
		if _, err := io.ReadFull(conn, binaryHead); err != nil {
			fmt.Println("read err:", err)
		}
		msgHead, err := dp.Unpack(binaryHead)
		if err != nil {
			fmt.Println("client unpack err:", err)
			break
		}
		if msgHead.GetMsgLen() > 0 {
			msg := msgHead.(*znet.Message)
			msg.Data = make([]byte, msg.GetMsgLen())
			if _, err := io.ReadFull(conn, msg.Data); err != nil {
				fmt.Println("read msg data err:", err)
				break
			}
			fmt.Println("---> Recv Server msg: id=", msg.GetMsgId(), "len=", msg.GetMsgLen(), "data=", string(msg.GetData()))

		}

		// cup阻塞
		time.Sleep(1 * time.Second)
	}
}
